package com.firemoss.magicbus.rpc.mock
{
	import com.firemoss.magicbus.rpc.ServiceMethod;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;

	[DefaultProperty("result")]
	public class MockServiceMethod extends ServiceMethod
	{

		public var returnValue : *;
		public var returnValueFactory : IMockReturnValueFactory
		
		public var delay : Number = 1000

		public function MockServiceMethod(remoteObject:RemoteObject=null, name:String=null)
		{
			super(remoteObject, name);
		}
		
		override public function send(... args:Array):AsyncToken
		{
			var originalArguments : Array = new Array()
			
			for each ( var arg : * in args )
			{
				originalArguments.push( arg )
			}

			executeBeforeChain( args )
			
			var mockReturnValue : * = null
			
			if ( returnValue && !returnValueFactory )
			{
				mockReturnValue = returnValue
			} 
			else if ( returnValueFactory )
			{
				mockReturnValue = returnValueFactory.create( args )
			}
			
			sendBeforeNotifications( args )
			
			var token : AsyncToken = new MockAsyncToken( mockReturnValue, delay )
			
			token.originalArguments = originalArguments
			token.filteredArguments = args

			addResponders( token )

			return token
		}
		
		override protected function addResponders( token : AsyncToken ) : void
		{
			token.addResponder( new Responder( onResponse, null ) )
			
			super.addResponders( token )
		}
		
		private function onResponse( event : ResultEvent ) : void
		{
			var filterResponse : * = rpcService.convertResultHandler.apply( rpcService, [ event.result, this ] )
			
			MockResultEvent( event ).updateResult( filterResponse )
		}
	}
}